//
//  TSRegisterViewController.swift
//  TopStock
//
//  Created by dyd on 2017/8/8.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit

class TSRegisterViewController: UIViewController {
    @IBOutlet weak var getVerifyButton: UIButton!
    @IBOutlet weak var telPhoneNumTextField: UITextField!
    @IBOutlet weak var verifyTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var checkPasswordTextField: UITextField!
    @IBOutlet weak var inviteCodeTextField: UITextField!
    @IBOutlet weak var checkButton: UIButton!
    var checkStatus:Bool = false
    var isPhoneRegister:Bool = true
    private var timer: Timer?
    let tsRequest = TSRequestData()

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBarAppearance()

        // Do any additional setup after loading the view.
    }
    
    func setNavBarAppearance(){
        let navBar=UINavigationBar.appearance()
        //.设置导航栏标题颜色
        navBar.titleTextAttributes = NavBarTitleTextAttributes
        //.设置导航栏按钮颜色
        navBar.tintColor = UIColor.lightGray
        //.设置导航栏背景颜色
        navBar.barTintColor = BarTintColor
        UIApplication.shared.statusBarStyle = .lightContent
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backItemAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

    //MARK: - 获取验证码
    @IBAction func getVerifyAction(_ sender: UIButton) {
        let telPhoneNum = telPhoneNumTextField.text
        if (telPhoneNum?.isEmpty)!{
             showAlertView(title: nil, message: "请输入手机号码")
            return
        }
        let isTelNumbe = TSMobileNumberManger.isTelPhoneNumber(telNumber: telPhoneNumTextField.text!)
        if (!isTelNumbe){
            showAlertView(title: nil, message: "请输入正确手机号码")
            return
        }else{
            _ = tsRequest.getCode(phoneNumber: telPhoneNum!, verify_type: 0)
        }
        getVerifyButton.backgroundColor = BtnTimingBackColor
        getVerifyButton.isEnabled = false
        self.remainingSeconds = 59
        self.isCommence = !self.isCommence
    }
    
    //倒计时的时间计算器
    private var isCommence: Bool = false {//是否开始计时
        willSet(newValue) {
            if newValue {
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
            } else {
                timer?.invalidate()
                timer = nil
            }
        }
    }
    
    //倒计时数
    private var remainingSeconds: Int = 0 {//remainingSeconds数值改变时 江将会调用willSet方法
        willSet(newSeconds) {
            let seconds = newSeconds%60
            getVerifyButton.setTitle(NSString(format: "%02ds", seconds) as String, for: .normal)
        }
    }
    
    // 更新时间
    func updateTimer(timer: Timer) {
        if remainingSeconds > 0 {
            remainingSeconds -= 1
        }
        if remainingSeconds == 0 {
            getVerifyButton.setTitle("获取验证码", for: .normal)
            getVerifyButton.isEnabled = true
            getVerifyButton.backgroundColor = BtnBackColor
            isCommence = !isCommence
            timer.invalidate()
        }
    }
    
    //MARK: - 手机号码注册
    @IBAction func confirmBtnAction(_ sender: UIButton){
        if !checkStatus
        {
            showAlertView(title: nil, message: "同意协议方可注册")
            return
        }
        let phoneNum = telPhoneNumTextField.text
        let password = passwordTextField.text
        let checkPassword = checkPasswordTextField.text
        let verifyCode = verifyTextField.text
        let inviteCode = inviteCodeTextField.text
        let isSure = telPoneNumAndPasswordDetection(phoneNum:phoneNum,
                                                    verifyCode:verifyCode,
                                                    password:password,
                                                    checkPassword:checkPassword)
        if isSure{
            let requestDic = tsRequest.register(phoneNumber: phoneNum!,
                                              password: password!,
                                              verifyCcode: verifyCode!,
                                              inviteCode: inviteCode,
                                              isPhoneRegister: isPhoneRegister)
            if requestDic != nil{
                let success:Bool = requestDic!["success"]! as! Bool
                if success{
                    if isPhoneRegister{
                        let accessTokenDic = requestDic?["data"] as! NSDictionary
                        let accessToken = accessTokenDic["access_token"] as? String
                        if (accessToken != nil){
                            UserDefaults.standard.set(accessToken, forKey: KAccessToken)
                        }
                        UserDefaults.standard.set(phoneNum, forKey: KPhoneNumberKey)
                        showContainerViewController(registerRelust: true)
                    }else{
                        let tmpDic = tsRequest.wechatLogin()
                        if (tmpDic != nil)
                        {
                            //获取微信的Token
                            let dataDic = tmpDic?["data"] as? NSDictionary
                            if dataDic != nil{
                                let token = dataDic?["access_token"] as? String
                                if token != nil{
                                    UserDefaults.standard.set(token, forKey: KAccessToken)
                                    NotificationCenter.default.post(name:NSNotification.Name(rawValue: "webViewRefresh"), object: nil, userInfo: nil)
                                    self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
                                }else{
                                    showAlertView(title: nil, message: "微信登陆失败")
                                }
                            }else{
                                showAlertView(title: nil, message: "微信注册失败")
                            }
                        }
                    }
                }else{
                    let errorDic = requestDic!["error"]! as! NSDictionary
                    let errorStr = errorDic["errorInfo"] as! String
                    if errorStr.contains("账号已注册"){
                        showAlertView(title: nil, message: errorStr)
                    }else{
                        showContainerViewController(registerRelust: false)
                    }
                }
            }else{
                showAlertView(title: nil, message: "请检查网络")
            }
        }
    }
    
    //输入号码和密码前需要检查
    func telPoneNumAndPasswordDetection(phoneNum:String?,
                                        verifyCode:String?,
                                        password:String?,
                                        checkPassword:String?) ->Bool{
        let isTelNumbe = TSMobileNumberManger.isTelPhoneNumber(telNumber: phoneNum!)
        if (!isTelNumbe){
            showAlertView(title: nil, message: "请输入正确手机号码")
            return false
        }
        
        if (verifyCode?.isEmpty)!{
            showAlertView(title: nil, message: "验证码不能为空")
            return false
        }else{
            let requestDic = checkVerifyCode()
            let success = requestDic["success"] as! Bool
            let errorDic = requestDic["error"]! as? NSDictionary
            let errorStr = errorDic?["errorInfo"] as? String
            if !success{
                showAlertView(title: nil, message: errorStr)
                return false
            }
        }
        if (password?.isEmpty)! && (checkPassword?.isEmpty)!{
            showAlertView(title: nil, message: "密码不能为空")
            return false
        }else if (password != checkPassword){
            showAlertView(title: nil, message: "两次输入的密码不一样")
            return false
        }
        else{
            return true
        }
    }
    
    //检验验证码
    func checkVerifyCode() ->NSDictionary
    {
        let phoneNum = telPhoneNumTextField.text
        let verifyCode = verifyTextField.text
        let requestDic = tsRequest.checkVerifyCode(phoneNumber: phoneNum!, verifyCcode: verifyCode!,verify_type: 0)
        print("requestDic =>:\(requestDic)")
        return requestDic
        
    }
    //Alert的显示
    func showAlertView(title:String?,message:String?)
    {
        let alertController = UIAlertController(title: title,
                                                message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: {
            action in
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    func showRootView()
    {
        NotificationCenter.default.post(name:NSNotification.Name(rawValue: "webViewRefresh"), object: nil, userInfo: nil)
        self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
//        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
//        let rootViewController = storyBoard.instantiateViewController(withIdentifier: "RootViewController") as! TSRootViewController
//        let rootNav = UINavigationController.init(rootViewController: rootViewController)
//        self.present(rootNav, animated: true, completion: nil)
    }
    
    
    @IBAction func hideKeyboard(_ sender: UITapGestureRecognizer)
    {
        telPhoneNumTextField.resignFirstResponder()
        verifyTextField.resignFirstResponder()
        passwordTextField.resignFirstResponder()
        checkPasswordTextField.resignFirstResponder()
        inviteCodeTextField.resignFirstResponder()
    }
    
    func alertViewController(title:String?,message:String?){
        let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "确定", style: .`default`, handler: {
            (UIAlertAction) -> Void in
            self.showRootView()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    //显示注册结果画面
    func showContainerViewController(registerRelust:Bool)
    {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
        let containerViewController = storyBoard.instantiateViewController(withIdentifier: "ContainerViewController") as! TSContainerViewController
        containerViewController.registerRelust = registerRelust
        self.present(containerViewController, animated: true, completion: nil)
    }
    
    @IBAction func checkButtonAction(_ sender: UIButton)
    {
        if checkStatus{
            checkButton.setImage(UIImage.init("checkbox_unchecked.png"), for: .normal)
            checkStatus = false
        }else{
            checkButton.setImage(UIImage.init("checkbox_checked"), for: .normal)
            checkStatus = true
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
